package main.com.votes.controller;

import main.com.votes.dao.UserDao;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (registerUser(username, password)) {
            response.sendRedirect("admin/regS.jsp");
        } else {
            request.setAttribute("msg", "注册失败，请重试");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        }
    }

    private boolean registerUser(String username, String password) {
        try {
            int update = userDao.registerUser(username, password);
            if (update == 1) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
